import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import './index.css'
export default class index extends Component {
  state = {
    users: [],
    isFirst: true,//是否第一次打开页面
    isLoading: false,//是否处于加载中
    err: ''//错误信息
  }
  // 接收数据-订阅消息
  componentDidMount() {
    // 给发布订阅命名，传递一个函数，接收message和data，_是占位符
    this.token = PubSub.subscribe('listStateChange', (_, data) => {
      const {users, isFirst, isLoading, err} = data
      this.setState({users, isFirst, isLoading, err})
      console.log(data)
    })
  }
  componentWillUnmount() {
    PubSub.unsubscribe(this.token)
  }

  render() {
    // const {users, isLoading, err, isFirst} = this.props
    const {users, isLoading, err, isFirst} = this.state
    return (
      <div>
        <div className="row">
          {
            isFirst? <h2 style={{margin: 20+'px'}}>欢迎使用</h2> :
            isLoading? <h2 style={{margin: 20+'px'}}>努力加载中</h2> :
            err? <h2 style={{margin: 20+'px'}}>{err}</h2> :
            users?.map(user => {
              return (
                <div key={user.id} className="card">
                  <a  rel="noreferrer" href={user.html_url} target="_blank">
                    <img alt=""  src={user.avatar_url}style={{width: 100+'px'}}/>
                  </a>
                  <p className="card-text">{user.login}</p>
                </div>
              )
            })
          }
        </div>
      </div>
    )
  }
}
